package com.example.forum.service.imp;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.mapper.ArticleMapper;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.IArticleService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImp implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private BoardServiceImp boardServiceImp;
    @Autowired
    private UserServiceImp userServiceImp;

    @Override
    public void create(Article article) {
        //进行参数的校验
        if(article == null || article.getUserId() == null
        || article.getBoardId() == null
        || !StringUtils.hasLength(article.getContent())
        || !StringUtils.hasLength(article.getTitle())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0); // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //进行创建文章的操作
        int result = articleMapper.insertSelective(article);
        if(result != 1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        //更新这里的用户表数据以及板块表数据
        //这里要进行校验的操作，利用事务进行轮滚或者是提交
        User user = userServiceImp.selectById(article.getUserId());

        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        userServiceImp.addOneArticleCountById(user.getId());

        Board board = boardServiceImp.selectById(article.getBoardId());
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getBoardId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        boardServiceImp.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString()
                + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId()
                + ", article id = "+article.getId() + "发帖成功");
    }

    @Override
    public List<Article> selectAll() {
         List<Article> articles = articleMapper.selectAll();
         return articles;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //参数的校验
        if(boardId == null || boardId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询这里的板块文章信息
        List<Article> articles = articleMapper.selectByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取查询
        Article article = articleMapper.selectDetailById(id);

        if(article == null){
            //说明这里的板块不存在或者被删除了
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_NOT_EXISTS));
        }

        //修改浏览量
        Article updataArticle = new Article();
        updataArticle.setId(id);
        updataArticle.setVisitCount(article.getVisitCount() + 1);

        int row = articleMapper.updateByPrimaryKeySelective(updataArticle);

        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //修改对象中的浏览量,数据过时，需要进行更新操作
        article.setVisitCount(article.getVisitCount() + 1);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //首先直接进行非空校验
        if(id == null || id <= 0
        ||!StringUtils.hasLength(title)
        ||!StringUtils.hasLength(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //更新文章（编辑）
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());

        //更新
         int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
         if(row != 1){
             log.warn(ResultCode.ERROR_SERVICES.toString());
             throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
         }

    }

    @Override
    public Article selectById(Long id) {
        //参数校验
         if(id == null || id<= 0){
             log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
             throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
         }

         Article article = articleMapper.selectByPrimaryKey(id);
         return article;
    }

    @Override
    public void thumbsUpById(Long id) {
        //参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //获取帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);

        //帖子对象校验
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //构造更新数据
        Article updateArticle = new Article();

        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);

        //点赞没必要进行时间的更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Long id) {
        //先进行数据的校验
        if (id == null || id <= 0) {
            // 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子对象，并进行校验
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article.getDeleteState() == 1 || article == null){
            //说明文章不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState() == 1){
            //说明帖子状态异常
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw  new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //更新梯子的删除状态
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte)1);

        //判断是否更新成功
        int result = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(result != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //更新用户表
        userServiceImp.subOneArticleCountById(article.getUserId());

        //更新板块表
        boardServiceImp.subOneArticleCountById(article.getBoardId());

        //打印更新成功日志
        log.info("文章删除成功，文章id：" + article.getId() + " 用户数据更新成功，用户id: " + article.getUserId()
        + " 板块数据更新成功，板块id: " + article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //首先进行参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //进行文章的校验
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //文章状态检验
        if(article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造更新对象
        Article updataArticle = new Article();
        updataArticle.setId(article.getId());
        updataArticle.setReplyCount(article.getReplyCount() + 1);
        updataArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updataArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId == null || userId <= 0){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户是否存在
        User user =userServiceImp.selectById(userId);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        List<Article> results = articleMapper.selectByUserId(userId);

        return results;
    }
}
